package org.arain.baseii.system.log;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.arain.baseii.common.CommonServiceImpl;
import org.arain.baseii.grid.GridData;
import org.arain.baseii.grid.QueryParam;
import org.arain.baseii.mapper.SysLogMapper;
import org.arain.baseii.pojo.SysLog;
import org.arain.baseii.pojo.SysLogExample;
import org.arain.baseii.pojo.SysLogExample.Criteria;
import org.arain.baseii.utils.AppUtils;
import org.arain.baseii.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
/**
 * 
* <p>Title:SystemLogServiceImpl </p>
* @author Arain
* @date2017年9月6日
 */
@Service
public class SystemLogServiceImpl extends CommonServiceImpl<SystemLogDto> implements SystemLogService{
	@Autowired
	private SysLogMapper sysLogMapper;
	@Override
	public void save_01(SystemLogDto dto) {
		SysLog log = new SysLog();
		AppUtils.copyProperties(log, dto);
		log.setLoginTime(new Date());
		sysLogMapper.insert(log);
	}
	@Override
	public String load_grid(QueryParam param) {
		SystemLogDto dto = new SystemLogDto();
		try {
			dto = this.jsonToObject(param.getFilterRules(), dto);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		JSONArray array = new JSONArray();
		SysLogExample example = new SysLogExample();
		Criteria criteria = example.createCriteria().andOrgidEqualTo(AppUtils.getOrgId());
		if(StringUtils.isNotBlank(param.getOrder()) && StringUtils.isNotBlank(param.getSort())) {
			example.setOrderByClause(param.getSort()+" "+param.getOrder());
		}
		if(StringUtils.isNotBlank(dto.getUsername())) {
			criteria.andUsernameLike("%"+dto.getUsername()+"%");
		}
		
		PageHelper.startPage(param.getPage(), param.getRows());
		List<SysLog> list = sysLogMapper.selectByExample(example);
		int countByExample = sysLogMapper.countByExample(example);
		for (SysLog sysLog : list) {
			JSONObject object = new JSONObject();
			object.put("id", sysLog.getId());
			object.put("mac", sysLog.getMac());
			object.put("username", sysLog.getUsername());
			object.put("ip", sysLog.getIp());
			object.put("loginTime", TimeUtil.format(sysLog.getLoginTime()));
			
			array.add(object);
		}
		GridData data = new GridData();
		data.setTotal(countByExample);
		data.setRows(array);
		return GridData.gridToJson(data);
	}
	@Override
	public SystemLogDto load_01(SystemLogDto dto) {
		SysLog sysLog = sysLogMapper.selectByPrimaryKey(Long.valueOf(dto.getId()));
		AppUtils.copyProperties(dto, sysLog);
		return dto;
	}

}
